﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using CxExtension.System.Diagnostics;
using JetBrains.Annotations;
using Debug = UnityEngine.Debug;

namespace CxExtension
{
	public class FileUtil
	{
		public static bool Rename(string oldFile, string newFile)
		{
			var hasFile = DeleteSafe(newFile);
			File.Move(oldFile,newFile);
			return hasFile;
		}
		/// <summary>
		/// if exists then delete it
		/// </summary>
		/// <param name="file"></param>
		/// <returns>if exists return true</returns>
		public static bool DeleteSafe(string file)
		{
			if (File.Exists(file))
			{
				File.Delete(file);
				return true;
			}
			return false;
		}
		public static string GetHashStr(string file)
		{
			//ProfilerF.BeginSample("FileUtil.GetHashStr" + file,100);

			var str = string.Empty;
			using (var stream = File.Open(file, FileMode.Open))
			{
				str = MD5Util.GetHashStr(stream);
			}
			
			//ProfilerF.EndSample();
			return str;
		}

		/// <summary>
		/// copy file,if src equal dest file,then not copy
		/// </summary>
		/// <param name="src"></param>
		/// <param name="dest"></param>
		/// <param name="overwrite">if  true then force replace copy overwrite to dest</param>
		/// <returns>if copy succes then return true</returns>
		public static bool Copy(string src,string dest,bool overwrite = true)
		{
			var equal = Equal(src,dest) && overwrite == false;
			if (equal ) { return false; }

			File.Copy(src,dest,true);
			return true;
		}
		/// <summary>
		/// copy unity meta file
		/// </summary>
		/// <param name="src"></param>
		/// <param name="dest"></param>
		/// <param name="overwrite"></param>
		/// <returns></returns>
		public static bool CopyMeta(string src, string dest, bool overwrite = true)
		{
			src = src + ".meta";
			dest = dest + ".meta";
			return Copy(src, dest, overwrite);
		}

		/// <summary>
		/// check src and dest file equal
		/// </summary>
		/// <param name="src"></param>
		/// <param name="dest"></param>
		/// <returns></returns>
		public static bool Equal([NotNull] string src, [NotNull] string dest,bool checkMd5 = false)
		{
			if (src == null) throw new ArgumentNullException("src");
			if (dest == null) throw new ArgumentNullException("dest");

			var info1 = new FileInfo(src);
			var info2 = new FileInfo(dest);
			var exit1 = info1.Exists;
			var exit2 = info2.Exists;
			if (!exit2 || !exit1) return false;

			if (info1.Length != info2.Length)
			{
				return false;
			}

			//return true;
			if (info1.LastWriteTimeUtc == info2.LastWriteTimeUtc && info1.Length == info2.Length)
			{
				return true;
			}

			if (checkMd5)
			{
				var md1 = GetHashStr(src);
				var md2 = GetHashStr(dest);

				return md1 == md2;
			}
			else
			{
				return false;
			}

		}


		public static void OpenText(string file,Action<StringBuilder> action)
		{
			var txt = File.ReadAllText(file);
			var bld = new StringBuilder(txt);
			action(bld);
			File.WriteAllText(file,bld.ToString());
		}

	}
}
